import store from "@/store";
import router from "@/router";
import accessEnum from "@/access/accessEnum";
import checkAccess from "@/access/checkAccess";

router.beforeEach(async (to, from, next) => {
  let loginUser = store.state.user.loginUser;
  // 如果之前没有登录过，自动登录
  if (!loginUser || !loginUser.userRole) {
    //加await 是为了等用户登录成功之后，在执行后续的代码
    await store.dispatch("user/getLoginUser");
    loginUser = store.state.user.loginUser;
  }

  const needAccess = (to.meta?.access as string) ?? accessEnum.NOT_LOGIN;
  //要跳转的页面必须要登录
  if (needAccess !== accessEnum.NOT_LOGIN) {
    // 如果没登录，直接跳转到登录页面
    if (
      !loginUser ||
      !loginUser.userRole ||
      loginUser.userRole === accessEnum.NOT_LOGIN
    ) {
      next(`/user/login?redirect=${to.fullPath}`);
      return;
    }
    // 如果已经登录了，权限不足
    if (!checkAccess(loginUser, needAccess)) {
      next(`/noAuth`);
      return;
    }
  }
  next();
});
